package com.yunkaweilai.android.activity.member;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.lazylibrary.util.StringUtils;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.CaptureActivity;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.CommonConstants;
import com.yunkaweilai.android.interfaces.PopupAddMemberMoney;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.member.MemberHeadModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.TitleBuilder;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.popup.MemberAddMoneyPopup;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 换卡
 * Created by Administrator on 2017/7/4.
 */

public class MemberChangeCardActivity extends BaseActivity implements PopupAddMemberMoney {

    public static final String MEMBER_CHANGE_MODEL = "Recharge_MEMBER_MODEL";
    public static final String MEMBER_CHANGE_BUNDLE = "Recharge_MEMBER_BUNDLE";
    @BindView(R.id.id_img_head)
    ImageView idImgHead;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.id_tvcard_number)
    TextView idTvcardNumber;
    @BindView(R.id.id_tv_card_infor)
    TextView idTvCardInfor;
    @BindView(R.id.id_tv_now_card)
    TextView idTvNowCard;
    @BindView(R.id.id_edt_new_card)
    EditText idEdtNewCard;
    @BindView(R.id.id_edt_new_space_card)
    EditText idEdtNewSpaceCard;
    @BindView(R.id.id_tv_now_spare_card)
    TextView idTvNowSpareCard;
    @BindView(R.id.titlebar_iv_left)
    ImageView titlebarIvLeft;
    @BindView(R.id.titlebar_tv_left)
    TextView titlebarTvLeft;
    @BindView(R.id.titlebar_tv)
    TextView titlebarTv;
    @BindView(R.id.titlebar_iv_right_2)
    ImageView titlebarIvRight2;
    @BindView(R.id.titlebar_iv_right)
    ImageView titlebarIvRight;
    @BindView(R.id.titlebar_tv_right)
    TextView titlebarTvRight;
    @BindView(R.id.id_view_underline)
    View idViewUnderline;
    @BindView(R.id.rl_titlebar)
    RelativeLayout rlTitlebar;
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;
    @BindView(R.id.id_img_code)
    ImageView idImgCode;
    private MemberHeadModel model;
    private String card_no = "";//卡号
    private boolean single_card_no = true;//卡号是否存在
    private boolean spare_card_no_flag = true;//备用卡号是否存在
    private String spare_card_no = "";//备用卡号
    private String is_sparecard_no = "0";
    private Handler handler = new Handler();
    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable CardNoRun = new Runnable() {
        @Override
        public void run() {
            //在这里调用服务器的接口，获取数据
            checkCardNo();
        }
    };
    private Runnable SpareCardNoRun = new Runnable() {
        @Override
        public void run() {
            //在这里调用服务器的接口，获取数据
            checkSpareCardNo();
        }
    };

    public static void actionStart(Context context, MemberHeadModel model) {
        Intent intent = new Intent(context, MemberChangeCardActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(MEMBER_CHANGE_MODEL, model);
        intent.putExtra(MEMBER_CHANGE_BUNDLE, bundle);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_member_change_card);
        ButterKnife.bind(this);
        model = (MemberHeadModel) getIntent().getBundleExtra(MEMBER_CHANGE_BUNDLE).getSerializable(MEMBER_CHANGE_MODEL);


        idTvNowCard.setText(model.getCard_no());
        idTvNowSpareCard.setText(model.getSparecard_no());
        initHeadView();
        initClick();

    }

    private void initClick() {
        idEdtNewCard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (CardNoRun != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler.removeCallbacks(CardNoRun);
                }
                card_no = s.toString();
                if (!model.getCard_no().equals(card_no + "")) {
                    //延迟800ms，如果不再输入字符，则执行该线程的run方法
                    if (!StringUtils.isEmpty(card_no)) {
                        handler.postDelayed(CardNoRun, 800);
                    }
                }
            }
        });

        idEdtNewSpaceCard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (SpareCardNoRun != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler.removeCallbacks(SpareCardNoRun);
                }
                spare_card_no = s.toString();

                if (!model.getSparecard_no().equals(spare_card_no + "")) {
                    //延迟800ms，如果不再输入字符，则执行该线程的run方法
                    if (!StringUtils.isEmpty(spare_card_no)) {
                        handler.postDelayed(SpareCardNoRun, 800);
                        is_sparecard_no = "1";
                    } else {
                        is_sparecard_no = "0";
                    }
                }
            }
        });

        idImgHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.ImageEnlage(mAc, "1", model.getMember_avatar(), model.getMember_sex());
            }
        });

        idImgCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCameraManifest();
            }
        });

    }

    //头部信息
    private void initHeadView() {
        new TitleBuilder(mAc).setTitleText("换卡").setLeftImage(R.mipmap.ic_go_back)
                .setRightText("保存").setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }).setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //保存
                isRight();
            }
        });
        Utils.MemberHeadImg(mAc, model.getMember_avatar(), model.getMember_sex(), idImgHead);
        idTvName.setText(model.getMember_name() + " (" + model.getLevel_name() + ": " + model.getCard_no() + ")");
        idTvCardInfor.setText("折扣：" + model.getDiscount() / 10 + "折   积分：" + model.getMember_points() + "   余额：" + model.getMember_price());
    }

    //验证参数是否完全
    private void isRight() {
        if (StringUtils.isEmpty(idEdtNewCard.getText().toString())) {
            showToast("卡号不能为空");
            return;
        }
        if (idTvNowCard.getText().toString().equals(idEdtNewCard.getText().toString())){
            showToast("新卡号不能与原卡号相同");
            return;
        }
        if (!single_card_no) {
            showToast("卡号已存在");
            return;
        }
        if (!spare_card_no_flag) {
            showToast("备用卡号已被存在");
            return;
        }
        if (idEdtNewCard.getText().toString().equals(idEdtNewSpaceCard.getText().toString())) {
            showToast("卡号与备用卡号不能相同");
            return;
        }
        String arrived_amount = model.getActivate_amount();
        if (!StringUtils.isEmpty(arrived_amount) && Float.parseFloat(arrived_amount) > 0) {
            MemberAddMoneyPopup memberAddMoneyPopup = new MemberAddMoneyPopup(mAc, Float.parseFloat(arrived_amount));
            memberAddMoneyPopup.setMemberMoney(this);
            memberAddMoneyPopup.showPopupWindow();
        } else {
            showProgressDialog("请稍等，正在换卡...");
            initHttp("0", "0", "");
        }
    }

    private void initHttp(String payment, String price, String type) {
        HttpRequest.postUrl(Api.UPDATE_CARD_NO)
                .addParams("other", "CardNo")
                .addParams("id", model.getId())
                .addParams("change_cardno", idEdtNewCard.getText().toString())
                .addParams("change_sparecardno", idEdtNewSpaceCard.getText().toString())
                .addParams("is_sparecard_no", is_sparecard_no)
                .addParams("payInfo[payment_type]", type)
                .addParams("payInfo[cash_price]", price)
                .addParams("payInfo[bank_price]", price)
                .addParams("payInfo[alipay_price]", price)
                .addParams("payInfo[wechat_price]", price)
                .addParams("payment", payment)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            showToast("修改成功");
                            model.setCard_no(idEdtNewCard.getText().toString());
                            if (!StringUtils.isEmpty(idEdtNewSpaceCard.getText().toString())) {
                                model.setSparecard_no(idEdtNewSpaceCard.getText().toString());
                            }
                            EventBus.getDefault().post(new Event.TypeEvent(CommonConstants.MEMBER_LIST, true));
                            EventBus.getDefault().post(new Event.OtherTypeEvent(CommonConstants.MEMBER_INFO_LIST, true, model));
                            finish();
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onError(Exception e) {
                        showToast("系统错误");
                        dismissProgressDialog();
                    }
                });
    }

    //检验卡号是否存在
    private void checkCardNo() {
        HttpRequest.postUrl(Api.CHECKED_MEMBER_CARD_NO)
                .addParams("type", "cardno")
                .addParams("value", card_no)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        single_card_no = Utils.checkCode(mAc, json);
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }

    //检验备用卡号是否存在
    private void checkSpareCardNo() {
        HttpRequest.postUrl(Api.CHECKED_MEMBER_CARD_NO)
                .addParams("type", "sparecardno")
                .addParams("value", spare_card_no)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        spare_card_no_flag = Utils.checkCode(mAc, json);
                    }

                    @Override
                    public void onError(Exception e) {
                        spare_card_no = "";
                    }
                });
    }

    @Override
    public void addMoney(String prcie, String type) {
        showProgressDialog("请稍等，正在换卡...");
        initHttp(model.getActivate_amount(), prcie, type);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                switch (requestCode) {
                    case 444://二维码
                        Bundle bundle = data.getExtras();
                        if (bundle == null) {
                            return;
                        }
                        String result = bundle.getString(CaptureActivity.RESULT);
                        if (model.getCard_no().equals(result)){
                            showToast("新卡号与原卡号不能相同");
                        }else{
                            idEdtNewCard.setText(result);
                        }
//                        checkCardNo();
                        break;
                }
            }
        }
    }
    //获取照相机权限
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 1;

    private void getCameraManifest() {
        MPermissions.requestPermissions(this,MY_PERMISSIONS_REQUEST_CAMERA,Manifest.permission.CAMERA);
    }

    private void getCamera() {
        Intent intent = new Intent(mAc, CaptureActivity.class);
        startActivityForResult(intent, 444);
    }

    @PermissionGrant(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestSuccess(){
        getCamera();
    }
    @PermissionDenied(MY_PERMISSIONS_REQUEST_CAMERA)
    public void requestError(){
        showToast("授权失败！");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this,requestCode,permissions,grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
}
